<script setup>
import LogoAndSearchNav from "@/components/LogoAndSearchNav.vue";
import {delCarProductAPI, getCarList, updateCarProductAPI} from "@/api/car.js";
import {onBeforeMount, ref, watchEffect} from "vue";
import TailPrice from "@/components/TailPrice.vue";
import {getProductById} from "@/api/product.js";
import {showImagePreview} from "vant";
import 'vant/es/image-preview/style'
import {PRODUCT_ROUTE} from "@/router/routes/product/product.js";
import {useRouter} from "vue-router";
import {showConfirmDialog} from 'vant';
import 'vant/es/dialog/style'
import {elErrorMessageTip} from "@/utils/MessageTipUtils.js";
import useOrderStore from "@/store/modules/OrderStore.js";
import {ORDER_ROUTE} from "@/router/routes/order/order.js";
import Null from "@/components/Null.vue";

const router = useRouter()

const carList = ref([])
const carListNums = ref([])
const allPrice = ref(0)
const carProductSelects = ref([])
const selectAll = ref(false)
const getCarListHandler = async () => {
  carList.value = await getCarList()
  carListNums.value = carList.value.map(
      item => item?.num
  )
  carList.value.forEach(
      () => carProductSelects.value.push(ref(false))
  )
}
onBeforeMount(async () => {
  await getCarListHandler()
})
const selectAllHandler = () => {
  if (selectAll.value) {
    carProductSelects.value = carProductSelects.value.map(() => ref(ref(true)))
  } else {
    carProductSelects.value = carProductSelects.value.map(() => ref(ref(false)))
  }
}
watchEffect(() => {
  allPrice.value = 0.0
  let cnt = 0
  for (let i = 0; i < carProductSelects.value.length; i++) {
    if (carProductSelects.value[i].value) {
      cnt++
      allPrice.value += carList.value[i].price * carListNums.value[i]
      allPrice.value = Math.round(allPrice.value * 100) / 100
    }
  }
  if (cnt === carList.value.length) {
    selectAll.value = true
  } else {
    selectAll.value = false
  }
})

const floatPanelVisible = ref(false)
const anchors = ref([window.innerHeight * 0.85])
const product = ref({})
const carProductId = ref(0)
const productId = ref(0)
const carProductNum = ref(0)
// 当前选中的商品图片、商品选项名称、商品选项价格
const productImgSelected = ref('')
const productOptionNameSelected = ref('')
const productOptionPriceSelected = ref(0)
const productOptionIdx = ref(0)
const newProductOptionId = ref(0)
const onOpenPanel = async (carProductId_, productId_, productOptionId, carProductIdx) => {
  carProductId.value = carProductId_
  productId.value = productId_
  carProductNum.value = carListNums.value[carProductIdx]
  // 获取商品信息
  product.value = await getProductById(productId_)
  let idx = 0;
  for (let i = 0; i < product.value.options.length; i++) {
    if (product.value.options[i].id === productOptionId) {
      idx = i
      break
    }
  }
  productOptionIdx.value = idx
  productImgSelected.value = product.value?.options[idx].img
  productOptionNameSelected.value = product?.value.options[idx].name
  productOptionPriceSelected.value = product?.value.options[idx].price
  newProductOptionId.value = product?.value.options[idx].id
  floatPanelVisible.value = true
}
const onClosePanel = () => {
  floatPanelVisible.value = false
}

// 商品选项选择
const selectProductOption = (option, idx) => {
  if (option?.stock <= 0) return
  productImgSelected.value = option?.img
  productOptionNameSelected.value = option?.name
  productOptionPriceSelected.value = option?.price
  newProductOptionId.value = option?.id
  productOptionIdx.value = idx
};

// 商品选项图片预览
const productOptionImgPreview = () => {
  showImagePreview([productImgSelected.value]);
}

// 前往商品详情页面
const goProductDetail = (productId) => {
  router.push({
    name: PRODUCT_ROUTE,
    query: {
      productId
    }
  })
}

const updateCarProductOption = async () => {
  const res = await updateCarProductAPI(carProductId.value, newProductOptionId.value, carProductNum.value, productId.value)
  if (res) {
    await getCarListHandler()
    onClosePanel()
  }
}
const updateCarProductNum = async (carProductId, idx) => {
  const res = await updateCarProductAPI(carProductId, null, carListNums.value[idx])
  if (res) {
    await getCarListHandler()
    onClosePanel()
  }
}
const delCarProduct = async (id) => {
  showConfirmDialog({
    message: '是否确认删除购物车商品'
  }).then(async () => {
    // on confirm
    const res = await delCarProductAPI(id)
    if (res) {
      await getCarListHandler()
    }
  }).catch(() => {
    // on cancel
  });
}

// 提交订单
const onCommit = () => {
  // 保存选择的要购买的书籍商品列表
  const orderProducts = []
  // 从购物车所有的书籍商品中选出用户选择的书籍商品
  for (let i = 0; i < carProductSelects.value.length; i++) {
    if (carProductSelects.value[i].value) {
      orderProducts.push(carList.value[i])
    }
  }
  // 用户未进行书籍商品的选择
  if (orderProducts.length <= 0) {
    elErrorMessageTip("还未选择商品")
    return
  }
  // 保存用户选择的要购买的书籍商品
  useOrderStore().saveProducts(orderProducts)
  // 前往确认订单页面
  router.push({name: ORDER_ROUTE})
}
</script>

<template>
  <div class="car overflow-hidden">
    <LogoAndSearchNav></LogoAndSearchNav>
    <!--<GoBackAndSearchNav :title="'购物车'" :placeholder="true"></GoBackAndSearchNav>-->
    <Null v-if="carList.length <= 0"></Null>
    <div v-else class="pb-16">
      <nut-swipe-group lock>
        <div v-for="(item, idx) in carList">
          <nut-swipe class="w-full mt-2" :name="item.id?.toString()">
            <div class="p-1 pl-2 bg-white dark:bg-neutral-900 flex justify-start items-stretch">
              <div class="flex-center">
                <van-checkbox class="pr-2 h-full" v-model="carProductSelects[idx].value"></van-checkbox>
              </div>
              <div class="option-img w-1/6 mr-2 rounded-xl overflow-hidden"
                   @click="goProductDetail(item?.productId)"
              >
                <img class="w-full h-full object-contain" :src="item?.img" alt="">
              </div>
              <div class="pt-1 w-8/12">
                <div class="truncate dark:text-gray-100"
                     @click="goProductDetail(item?.productId)"
                >{{ item?.title }}
                </div>
                <div
                    class="option-name mt-1 mb-1 p-0.5 pl-2 pr-2 rounded-md bg-gray-300 truncate text-gray-500 text-xs"
                    @click.self.stop="onOpenPanel(item?.id, item?.productId, item?.productOptionId, idx)"
                >{{ item?.name }}
                </div>
                <div class="flex justify-between items-center">
                  <TailPrice
                      :price="item?.price.toString()"
                      :is-start="false"
                      @click="goProductDetail(item?.productId)"
                  ></TailPrice>
                  <van-stepper
                      v-model="carListNums[idx]"
                      integer
                      @change="updateCarProductNum(item.id, idx)"
                      :min="1"
                      :max="item?.stock"
                      theme="round"
                      button-size="20"
                  />
                </div>
              </div>
            </div>
            <template #right>
              <nut-button shape="square"
                          style="height:100%"
                          type="danger"
                          @click="delCarProduct(item?.id)"
              >删除</nut-button>
            </template>
          </nut-swipe>
        </div>
      </nut-swipe-group>
    </div>
    <div class="w-screen p-2 bg-white dark:bg-neutral-900 fixed bottom-12 left-0 flex justify-between items-center">
      <van-checkbox v-model="selectAll" @click="selectAllHandler">全选</van-checkbox>
      <div class="flex justify-start items-center">
        <div class="mr-2 flex justify-start items-center">
          <span class="dark:text-gray-100">合计：</span>
          <TailPrice :price="allPrice.toString()" :is-start="false"></TailPrice>
        </div>
        <van-button
            color="linear-gradient(to right, #ff6034, #ee0a24)"
            round
            @click="onCommit"
        >
          提交订单
        </van-button>
      </div>
    </div>
    <van-overlay :show="floatPanelVisible" @click="onClosePanel" lock-scroll>
      <div class="flex-start-center pl-4 pr-4 pt-4">
        <div class="img w-16 h-16 mr-2 flex-nowrap">
          <img class="w-full h-full object-contain"
               :src="productImgSelected" alt=""
               @click.stop="productOptionImgPreview"
          >
        </div>
        <div class="name text-sm text-gray-100 w-5/6">
          {{ productOptionNameSelected }}
        </div>
      </div>
    </van-overlay>
    <van-floating-panel
        :content-draggable="true"
        :anchors="anchors"
        v-show="floatPanelVisible"
    >
      <div class="h-full flex flex-col justify-between">
        <div class="p-2">
          <div class="flex justify-between items-center">
            <TailPrice
                :price="productOptionPriceSelected.toString()"
                :isStart="false"
            ></TailPrice>
            <div class="mr-4 text-neutral-600 dark:text-gray-200" @click="onClosePanel">
              <span class="iconfont icon-close"></span>
            </div>
          </div>
          <div
              v-for="(item, idx) in product?.options"
              @click="selectProductOption(item, idx)"
              class="product-option bg-gray-50 dark:bg-neutral-950 dark:text-gray-100 mt-2 p-2 rounded-xl overflow-hidden flex justify-between items-center"
              :class="[productOptionIdx === idx ? 'product-option-selected' : '', item?.stock <= 0 ? 'text-gray-300' : '']"
          >
            <div class="flex-start-center">
              <div class="img w-12 h-12 mr-2">
                <img class="w-full h-full object-contain" :src="item.img" alt="">
              </div>
              <div class="name text-sm w-52">
                {{ item?.name }}
              </div>
            </div>
            <div class="price text-sm flex-nowrap">￥ {{ item?.price }}</div>
          </div>
        </div>
        <div class="p-4">
          <van-button color="linear-gradient(to right, #ff8a17, #ee0a24)"
                      @click="updateCarProductOption"
                      round block
          >
            确定
          </van-button>
        </div>
      </div>
    </van-floating-panel>
  </div>
</template>

<style scoped lang="scss">
.product-option {
  border: 1px solid transparent;
  font-weight: 300;
}

.product-option-selected {
  border: 1px solid #ff5000;
}

.option-img {
  min-width: 4.5rem;
  max-width: 6rem;
}

.option-name {
  width: min-content;
  max-width: 70%;
}
</style>